package cs342.uwosh.group1.mycontacts;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.mycontacts.R;
import com.mycontacts.R.layout;
import com.mycontacts.R.menu;

import cs342.uwosh.group1.mycontacts.Threads.CreateUserOnCloud;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;


public class Setup extends Activity {

	SharedPreferences mPrefs;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setup);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_setup, menu);
		return true;
	}
	
	public void confirming(View view){
		EditText u = (EditText)findViewById(R.id.uName);
		EditText p = (EditText)findViewById(R.id.pWord);
		EditText p2 = (EditText)findViewById(R.id.pWordConf);
		String user = u.getText().toString();
		String pass = p.getText().toString();
		String pass2 = p2.getText().toString();
		
		if(pass.equals(pass2)){
			//Asynchronously create new user
			int result = 0;
			
			//Check if device is connected to the internet
			ConnectivityManager connMgr = (ConnectivityManager) 
		        getSystemService(Context.CONNECTIVITY_SERVICE);
		    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		    if (networkInfo != null && networkInfo.isConnected()) {
		        result = attemptToCreateUser(user, pass);
		    } else {
		    	new AlertDialog.Builder(this)
			    .setTitle("Error")
			    .setMessage("A network connection is required to create a user.")
			    .setCancelable(false)
			    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			        public void onClick(DialogInterface dialog, int which) { 
			        	dialog.cancel();
			        }
			     })
			     .show();
		    }
			if(result !=0){
				//Save username/password
			    mPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
			    SharedPreferences.Editor edit = mPrefs.edit();
			    edit.putInt("uid", result);
			    edit.putString("username", user);
			    edit.putString("password", pass);
			    edit.putInt("ver", 0);
			    edit.commit();
			    MainActivity.signedIn = true;
			    MainActivity.changed = true;
				finish();
			}else{
				new AlertDialog.Builder(this)
			    .setTitle("Error")
			    .setMessage("That username is already taken.")
			    .setCancelable(false)
			    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			        public void onClick(DialogInterface dialog, int which) { 
			        	dialog.cancel();
			        }
			     })
			     .show();
			}	
		}else{
			TextView i = (TextView)findViewById(R.id.ErrorMsg);
			i.setVisibility(TextView.VISIBLE);
		}
	}
	
	
	public int attemptToCreateUser(String username, String password){
		URL url;
		String urlParameters = "?username='"+username+"'&password='"+password+"'";
		HttpURLConnection connection = null;
		try {
			//Setup connection
			url = new URL("http://softeng.cs.uwosh.edu/students/smithk58/project2/createUser.php"+urlParameters);
			connection = (HttpURLConnection)url.openConnection();
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");
	        connection.setDoInput(true);
	        connection.setDoOutput(true);
	        connection.setUseCaches(false);
			
	        //Send request
	        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
	        wr.writeBytes(urlParameters);
	        wr.flush();
	        wr.close();
	        
	        //Get Response (should be the users id in this case, which needs to be stored in preferences)
	        InputStream is = connection.getInputStream();
	        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
	        String line;
	        StringBuffer response = new StringBuffer(); 
	        while((line = rd.readLine()) != null) {
	          response.append(line);
	        }
	        rd.close();
	        //Convert result to int
	        int resultInt = Integer.parseInt(response.toString());
			//If result int is > 0 then it inserted successfully
			if(resultInt > 0){
				return resultInt;
			}else{//duplicate key
				return 0;
			}
	        
		} catch (MalformedURLException e) {
			return 0;
		} catch (IOException e) {
			return 0;
		}
		finally
        {
            if(connection != null)
              connection.disconnect();
        }
	}
	

}
